package com.yun.baymax.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocationClient;
import com.yun.baymax.R;
import com.yun.baymax.activity.account.BindEmailActivity;
import com.yun.baymax.activity.account.ChangePasswordActivity;
import com.yun.baymax.activity.account.ForgetPasswordActivity;
import com.yun.baymax.activity.account.LoginActivity;
import com.yun.baymax.base.LocationHelper;
import com.yun.baymax.bean.User;
import com.yun.baymax.cache.UserCache;
import com.yun.lib.fragment.BaseFragment;
import com.yun.lib.utils.SPUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;

public class SettingsFragment extends BaseFragment {
    private static Context context;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_comment)
    TextView tvComment;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_age)
    TextView tvAge;
    @BindView(R.id.tv_logout)
    AppCompatTextView tvLogout;
    @BindView(R.id.rl_sex)
    RelativeLayout rlSex;
    @BindView(R.id.rl_age)
    RelativeLayout rlAge;
    @BindView(R.id.tv_bind_email)
    AppCompatTextView tvBindEmail;
    @BindView(R.id.tv_reset_pwd)
    AppCompatTextView tvResetPwd;
    @BindView(R.id.tv_change_pwd)
    AppCompatTextView tvChangePwd;
    @BindView(R.id.share_location)
    SwitchCompat shareLocation;
    private User bmUser;
    private User localUser;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getContext();
    }

    @Override
    protected int setLayoutResourceId() {
        return R.layout.fragment_settings;
    }

    @Override
    protected void initViews(Bundle savedInstanceState, View view, LayoutInflater inflater) {
        ButterKnife.bind(this, view);
        initViewData();
    }

    @Override
    protected void loadData() {
    }

    private void initViewData() {
        localUser = UserCache.getInstance().getCurrentUser();
        bmUser = BmobUser.getCurrentUser(User.class);
        if (bmUser == null)
            return;
        localUser = localUser == null ? bmUser : localUser;
        String keyNickName = localUser.getNick();

        String keyComment = localUser.getContent();
        int keyAge = localUser.getAge();

        boolean keySex = localUser.getSex();

        tvNickname.setText(TextUtils.isEmpty(keyNickName) ? "点击设置昵称" : keyNickName);

        tvComment.setText(TextUtils.isEmpty(keyComment) ? "点击设置签名" : keyComment);

        tvAge.setText(keyAge == 0 ? "" : keyAge + "");

        tvSex.setText(keySex ? "男" : "女");

        String email = bmUser.getEMail();

        if (!TextUtils.isEmpty(email)) {
            tvBindEmail.setText(email);
        }

        shareLocation.setChecked((Boolean) SPUtils.get(context, "share_location", false));
        shareLocation.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SPUtils.put(context, "share_location", isChecked);
                AMapLocationClient mLocationClient = LocationHelper.getInstance().mLocationClient;
                if (mLocationClient.isStarted())
                    mLocationClient.stopLocation();
                else
                    mLocationClient.startLocation();
            }
        });

    }

    private void updateUserInfo(User user) {
        UserCache.getInstance().updateUser(localUser);
        localUser.setEmail(null);
        localUser.update(user.getObjectId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    showToast("更新成功");
                    initViewData();
                } else {
                    showToast("更新失败" + e.getMessage());
                }
            }
        });
    }

    @OnClick({R.id.tv_nickname, R.id.tv_comment, R.id.rl_sex, R.id.rl_age, R.id.tv_logout, R.id.tv_bind_email, R.id.tv_reset_pwd, R.id.tv_change_pwd})
    public void onClick(View view) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(context);
        switch (view.getId()) {
            case R.id.tv_nickname:
                showDialog("设置昵称", tvNickname.getText().toString(), new OnValueChangeListener() {
                    @Override
                    public void onChangedValue(String value) {
                        bmUser.setNick(value);
                        localUser.setNick(value);
                        updateUserInfo(bmUser);
                    }
                });

                break;
            case R.id.tv_comment:
                showDialog("设置签名", tvComment.getText().toString(), new OnValueChangeListener() {
                    @Override
                    public void onChangedValue(String value) {
                        bmUser.setContent(value);
                        localUser.setContent(value);
                        updateUserInfo(bmUser);
                    }
                });
                break;
            case R.id.rl_sex:
                dialog.setTitle("请选择性别")
                        .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("男", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                bmUser.setSex(true);
                                localUser.setSex(true);
                                updateUserInfo(bmUser);
                            }
                        })
                        .setNegativeButton("女", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                bmUser.setSex(false);
                                localUser.setSex(false);
                                updateUserInfo(bmUser);
                            }
                        }).show();
                break;
            case R.id.rl_age:

                showDialog("设置年龄", tvAge.getText().toString(), new OnValueChangeListener() {
                    @Override
                    public void onChangedValue(String value) {
                        if (TextUtils.isEmpty(value)) {
                            bmUser.setAge(0);
                            localUser.setAge(0);
                            updateUserInfo(bmUser);
                        } else {
                            try {
                                int i = Integer.parseInt(value);
                                bmUser.setAge(i);
                                localUser.setAge(i);
                                updateUserInfo(bmUser);
                            } catch (Exception e) {
                                showToast("年龄请输入数字");
                            }
                        }
                    }
                });
                break;
            case R.id.tv_logout:
                dialog.setMessage("确认退出?").setTitle("注销").setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        UserCache.getInstance().logOut();
                        goNext(getString(R.string.action_sign_in), LoginActivity.class);
                        getActivity().finish();
                    }
                }).show();
                break;
            case R.id.tv_bind_email:

                goNext(localUser.getEMail(), BindEmailActivity.class);

                break;

            case R.id.tv_change_pwd:

                if (bmUser != null) {
                    goNext(getString(R.string.activity_change_password), ChangePasswordActivity.class);
                } else {
                    showToast("请登录!");
                }

                break;
            case R.id.tv_reset_pwd:

                String email = localUser.getEMail();

                //bug 返回值为null
//                Boolean emailVerified = bmUser.getEmailVerified();

                if (email != null) {
                    goNext(localUser.getEMail(), ForgetPasswordActivity.class);
                } else {
                    showToast("请先绑定邮箱!");
                }

        }
    }


    private void showDialog(String title, final String value, final OnValueChangeListener listener) {

        AlertDialog.Builder dialog = new AlertDialog.Builder(context);

        final EditText et = new EditText(context);
        et.setText(TextUtils.isEmpty(value) ? "" : value);
        et.setSelection(TextUtils.isEmpty(value) ? 0 : value.length());
        dialog.setView(et);
        dialog.setTitle(title);
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String s = et.getText().toString();
                if (!TextUtils.equals(s, value) && listener != null) {
                    listener.onChangedValue(s);
                }
                dialogInterface.dismiss();
            }
        });

        dialog.show();

    }

    interface OnValueChangeListener {
        void onChangedValue(String value);
    }
}
